package com.inspur.gs.sbssdl.database.rysj.rysj.back.util;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

public class SQLUtil {

    /**
     * 插入操作
     *
     * @param dataTable 数据表名
     * @param set       Map例如：{'SHIP_NUMBER':'123456','SHIP_NAME':'test'}
     * @param where     Map例如：{'SHIP_NUMBER':'123456','SHIP_NAME':'test2'}
     */
    public String update(String dataTable, Map<String, Object> set, Map<String, Object> where) {

        StringBuilder sql = new StringBuilder("update " + dataTable + " set ");
        StringBuilder setStr = new StringBuilder(" ");
        StringBuilder whereStr = new StringBuilder(" where ");

        for (String key : set.keySet()) {
            setStr.append(key).append(" = ").append("'").append(set.get(key)).append("'").append(",");
        }
        setStr.delete(setStr.length() - 1, setStr.length());

        for (String key : where.keySet()) {
            whereStr.append(key).append(" = ").append("'").append(where.get(key)).append("'").append(" and ");
        }
        whereStr.delete(whereStr.length() - 4, whereStr.length());

        sql.append(setStr).append(whereStr);
        return sql.toString();
    }


    public static String insetSql(String tableName, HashMap<String, Object> value){
        String prefix = "insert into " + tableName;

        StringBuilder columnSql = new StringBuilder("(");
        StringBuilder valueSql = new StringBuilder(" VALUES (");

        value.forEach((k,v) -> {
            columnSql.append(k).append(",");
            if (v instanceof LocalDateTime){
                String timeFormatter = ((LocalDateTime) v).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                valueSql.append(String.format("TIMESTAMP '%s'", timeFormatter)).append(",");
            }else {
                valueSql.append("'").append(v).append("'").append(",");
            }
        });

        columnSql.deleteCharAt(columnSql.length()-1)
                .append(")");
        valueSql.deleteCharAt(valueSql.length()-1)
                .append(")");

        return prefix + columnSql + valueSql;
    }
}
